package com.gtw.modules.api.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.plugins.Page;
import com.gtw.common.annotation.LoginUserApi;
import com.gtw.common.utils.Query;
import com.gtw.common.utils.R;
import com.gtw.common.validator.Assert;
import com.gtw.dto.TbWalletDto;
import com.gtw.modules.api.service.TbUserBankCardService;
import com.gtw.modules.api.service.TbUserService;
import com.gtw.modules.api.service.TbWalletpaylogService;
import com.gtw.modules.entity.TbUser;
import com.gtw.modules.entity.TbUserBankCard;
import com.gtw.modules.entity.TbWalletPayLog;
import com.gtw.utils.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 钱包Controller
 * Created by wuye on 2018/3/13.
 */
@RestController
@RequestMapping("/api/wallet")
public class TbWalletController {

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbWalletpaylogService tbWalletpaylogService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private TbUserBankCardService tbUserBankCardService;



    /**
     * 查询用户钱包信息
     *
     * @return
     */
    @RequestMapping("/foundByUser")
    public R foundByUser(@LoginUserApi TbUser tbUser) {
        String msg = null;
        TbUser tuser = tbUserService.queryById(tbUser.getUserId());
        List<TbUserBankCard> tbUserBankCard = tbUserBankCardService.foundByIdBankCard2(tbUser.getUuid());

        TbWalletDto dto = new TbWalletDto();
        dto.setTbUser(tbUser);
        //可提现金额
        Float can_withdraw = Float.valueOf((tbUser.getBalance() + tbUser.getBalanceCommission()));
        //历史提现金额
        List<TbWalletPayLog> list = tbWalletpaylogService.queryByUid(tbUser.getUuid());
        Float historical_withdraw = 0f;
        for (TbWalletPayLog wpl : list) {
            historical_withdraw += wpl.getTotalfee();
        }
        dto.setCan_withdraw(can_withdraw);
        dto.setHistorical_withdraw(historical_withdraw);
        List<String> paylist = new ArrayList<>();
        paylist.add(PayType.CT_WX.getName());
//        paylist.add(PayType.ALI_WEB.getName());
//        paylist.add(PayType.CT_UN.getName());
        dto.setPaystatus(paylist);
        dto.setTbUserBankCard(tbUserBankCard);
        dto.setIsmessage(true);
        dto.setIspwd(true);
        if (tbUser.getPaypwd() == null) {
            dto.setIspwd(false);
        }
        if (tbUserBankCard == null) {
            dto.setIsmessage(false);
        }
        return R.ok().put("data", dto);
    }


    /**
     * 查询历史提现记录列表
     *
     * @param params
     * @returnapi
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, @LoginUserApi TbUser tbUser) {
        params.put("uid", tbUser.getUuid());
        //查询列表数据
        Query query = new Query(params);
        Page<TbWalletPayLog> pageUtil = new Page<TbWalletPayLog>(query.getPage(), query.getLimit());
        Page<TbWalletPayLog> page = tbWalletpaylogService.queryPageList(pageUtil, query);
        return R.ok().put("data", page);
    }


    /**
     * 设置/修改提现密码
     *
     * @return
     */
    @RequestMapping("/addPaypwd")
    public R addPayPwd(@LoginUserApi TbUser tbUser, @RequestParam String newpwd, @RequestParam String code) {
        Assert.isBlank(newpwd, "密码不能为空");
        Assert.isBlank(code, "验证码不能为空");
        //判断验证码是否正确
        String rcode = redisTemplate.opsForValue().get(tbUser.getMobile());
        if (rcode == null) {
            return R.error("验证码过期");
        }
        if (rcode.equals(code)) {
            tbUser.setPaypwd(DigestUtils.sha256Hex(newpwd));
            tbUserService.update(tbUser);
            return R.ok();
        } else {
            return R.error("验证码错误");
        }
    }

    /**
     * 修改手机号
     *
     * @return
     */
    @RequestMapping("/updatePhone")
    public R updatePhone(@LoginUserApi TbUser tbUser, @RequestParam String mobile, @RequestParam String code) {
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(code, "验证码不能为空");
        //判断验证码是否正确
        String rcode = redisTemplate.opsForValue().get(mobile);
        if (rcode == null) {
            return R.error("验证码过期");
        }
        if (rcode.equals(code)) {
            tbUser.setMobile(mobile);
            tbUserService.update(tbUser);
            return R.ok();
        } else {
            return R.error("验证码错误");
        }
    }


    private static int captchaExpires = 60; //超时时间一分钟

    /**
     * 获取修改支付密码短信验证码
     *
     * @param tbUser
     * @return
     * @throws ClientException
     */
    @RequestMapping("/getCode")
    public R getCode(@LoginUserApi TbUser tbUser) throws ClientException {
        String phone = tbUser.getMobile();
        //生成验证码
        String code = String.valueOf(new Random().nextInt(99999));
        //将验证码以<key,value>形式缓存到redis
        redisTemplate.opsForValue().set(phone, code);
        //设置过期时间
        redisTemplate.expire(phone, captchaExpires, TimeUnit.SECONDS);
        //调用第三方短信接口
        SendSmsResponse response = SmsDemo.sendSms(phone, Integer.valueOf(code));
        if ("isv.BUSINESS_LIMIT_CONTROL".equals(response.getCode())) {
            return R.error("一分钟内只能发一次");
        } else {
            return R.ok().put("response", response);
        }
    }


    /**
     * 设置/修改提现收款信息
     *
     * @return
     */
    @RequestMapping("/saveOrupdateBankCard")
    public R saveOrupdateBankCard(@LoginUserApi TbUser tbUser, @RequestParam String paytype, @RequestParam String bankcard,String bankType, @RequestParam String cardusername) {
//        //判断验证码是否正确
//        String rcode = redisTemplate.opsForValue().get(tbUser.getMobile());
//        if (rcode == null) {
//            return R.error("验证码过期");
//        }
//        if (rcode.equals(code)) {
        List<TbUserBankCard> tbUserBankCardList = tbUserBankCardService.foundByIdBankCard2(tbUser.getUuid());
        boolean isresult = false;
        TbUserBankCard tbUserBankCard = new TbUserBankCard();
        if (tbUserBankCardList.size() > 0) {
            for (TbUserBankCard tbk : tbUserBankCardList) {
                if (tbk.getBankcard().equals(bankcard)) {
                    isresult = true;
                    tbUserBankCard = tbk;
                }
            }
            if (!isresult) {
                tbUserBankCard.setPaytype(paytype);
                tbUserBankCard.setBankcard(bankcard);
                tbUserBankCard.setCardusername(cardusername);
                tbUserBankCard.setBankType(bankType);
                tbUserBankCardService.updateByPrimaryKey(tbUserBankCard);
            } else {
                TbUserBankCard tbUserBankCard1 = new TbUserBankCard();
                tbUserBankCard1.setPaytype(paytype);
                tbUserBankCard1.setBankcard(bankcard);
                tbUserBankCard1.setCardusername(cardusername);
                tbUserBankCard1.setCreatetime(new Date());
                tbUserBankCard1.setPhone(tbUser.getMobile());
                tbUserBankCard1.setUid(tbUser.getUuid());
                tbUserBankCard1.setBankType(bankType);
                tbUserBankCardService.insert(tbUserBankCard1);
            }
        }
        return R.ok();
//        } else {
//            return R.error("验证码错误");
//        }
    }

    /**
     * 根据用户UID查询提现收款信息
     *
     * @return
     */
    @RequestMapping("/foundByIdBankCard")
    public R foundByIdBankCard(@LoginUserApi TbUser tbUser) {
        List<TbUserBankCard> tbUserBankCard = tbUserBankCardService.foundByIdBankCard2(tbUser.getUuid());
        return R.ok().put("tbuserbankcard", tbUserBankCard);
    }


    /**
     * 申请提现
     *
     * @return
     */
    @RequestMapping("/applyWithdrawal")
    public R applyWithdrawal(@LoginUserApi TbUser tbUser, @RequestParam String pwd, @RequestParam Integer money, @RequestParam Integer type, @RequestParam Integer _id) {
        TbUser user = tbUserService.queryById(tbUser.getUserId());
        if (money > user.getBalance()) {
            return R.error().put("msg", "余额不足");
        }
        if (tbUser.getWithdrawaltimes() > 0) {
            tbUser.setWithdrawaltimes(tbUser.getWithdrawaltimes() - 1);

            if (user.getPaypwd().equals(DigestUtils.sha256Hex(pwd))) {
                TbWalletPayLog tbWalletPayLog = new TbWalletPayLog();
                tbWalletPayLog.setBillno(OrderUtil.getOrderNo());
                tbWalletPayLog.setCreatedate(new Date());
                TbUserBankCard tbUserBankCard = tbUserBankCardService.selectByPrimaryKey(_id);
                tbWalletPayLog.setCreateuser(tbUserBankCard.getCardusername());
                //支付状态
                tbWalletPayLog.setPaystatus(WithdrawStatus.review.getName());
                //支付类型
                if (type == 1) {
                    tbWalletPayLog.setPaytype(PayType.CT_WX.getName());
                } else {
                    tbWalletPayLog.setPaytype(PayType.CT_UN.getName());
                    tbWalletPayLog.setTitle(tbUserBankCard.getBankcard());
                }
                //返回类型
                tbWalletPayLog.setReturntype("NOTPAY");
                tbWalletPayLog.setTotalfee(money);
                tbWalletPayLog.setUid(user.getUuid());
                tbWalletPayLog.setUpdatedate(new Date());
                tbWalletPayLog.setUpdateuser(user.getUsername());
                //用户支付状态
//            tbWalletPayLog.setUserpaystatus(WithdrawStatus.review.getName());
                //回调状态
//            tbWalletPayLog.setWebhookstatus();
                tbWalletPayLog.setIddelete(false);
                //类型 0：提交申请  1：审核中  2：审核通过,待打款 3：审核未通过 4：已打款
                tbWalletPayLog.setType(1);
                tbWalletpaylogService.save(tbWalletPayLog);
                user.setBalance(user.getBalance() - money);
                tbUserService.update(user);
                return R.ok();
            } else {
                return R.error().put("msg", "提现密码错误");
            }
        } else {
            return R.error().put("msg", "本月提现次数已经使用完");
        }
    }
}